#include "udp_server_test.h"
#include "event_loop_thread.h"
#include "event_loop.h"
#include "udp_server.h"
#include <iostream>

using namespace std;
using namespace el;

el::UdpServerTest::UdpServerTest()
{
}

el::UdpServerTest::~UdpServerTest()
{
}

bool el::UdpServerTest::test()
{
	EventLoopThread thread;
	EventLoop* loop = thread.startLoop();

	SocketAddrIn server_addr(INADDR_LOOPBACK, 800);
	UdpServer* server = new UdpServer(loop, server_addr);
	server->setMessageCallback(UdpMessageCallback(this, &UdpServerTest::onMessage));
	server->start();

	for (size_t i = 0; i < 1024; i++)
	{
		Socket client(Socket::getUdpSocket());
		char buf[] = "echo";
		::sendto(client.fd(), buf, sizeof(buf), 0, (sockaddr*)&server_addr.sockaddr(), server_addr.lenght());
		cout << "client send:" << buf << endl;

		char read_buf[1024] = { 0 };
		::recvfrom(client.fd(), read_buf, sizeof(read_buf), 0, (sockaddr*)&server_addr.sockaddr(), &server_addr.lenght());
		cout << "client read:" << read_buf << endl;
		client.closeFD();
	}

	Sleep(500);
	server->stop();

	thread.quit();
	return true;
}

void el::UdpServerTest::onMessage(UdpServer * server)
{
	Buffer buf;
	SocketAddrIn addr;
	server->readData(buf, addr);
	cout << "server:" << buf.peekRead() << endl;
	server->sendData(buf, addr);
}
